package com.sddongyun.service.impl;

import com.alibaba.fastjson.JSON;
import com.sddongyun.common.*;
import com.sddongyun.common.entity.JHQrcodeRequest;
import com.sddongyun.dao.HisDao;
import com.sddongyun.service.PayService;

import java.io.*;
import java.lang.String;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.SystemDefaultCredentialsProvider;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;


import javax.jws.WebService;
import javax.xml.ws.BindingType;
import javax.xml.ws.soap.SOAPBinding;


import java.net.Socket;
import java.net.URLDecoder;
import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * Created by lenovo on 2019/4/17.
 */

@SuppressWarnings("ValidExternallyBoundObject")
@WebService(serviceName = "PayServer",targetNamespace = "http://service.sddongyun.com",endpointInterface = "com.sddongyun.service.PayService")
@Component
@BindingType(value = SOAPBinding.SOAP12HTTP_BINDING)
public class PayServiceImpl implements PayService {
    private Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
    @Autowired
    HisDao hisDao;
    @Autowired
    private payConfig Config;
    @Autowired
    private JHConfig jhConfig;
    @Value("${cdserver.yburl}")
    private String ybUrl;

    @Value("${cdserver.ybjjcode}")
    private String ybjjcode;
    @Value("${cdserver.pwd}")
    private String pwd;

//    @Autowired
//    private Client client;

    @Override
    public openServerResponse OpenServer(SortedMap<String, String> arg0) {
        arg0.put("mch_id",Config.mch_id );
        arg0.put("sign_type","MD5" );
        arg0.put("nonce_str", String.valueOf(new Date().getTime()));
        Map<String, String> params = SignUtils.paraFilter(arg0);
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        SignUtils.buildPayParams(buf,params,false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + Config.key, "utf-8");
        arg0.put("sign", sign);
        logger.info(JSON.toJSONString(arg0));
        HttpPost httpPost = new HttpPost(Config.req_url);
        StringEntity entityParams = new StringEntity(XmlUtils.parseXML(arg0),"utf-8");
        httpPost.setEntity(entityParams);
        httpPost.setHeader("Content-Type", "text/xml;charset=utf-8");
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        openServerResponse res = new openServerResponse();
        try {
            response = client.execute(httpPost);
            if(response != null && response.getEntity() != null){
                Map<String,String> resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");
               logger.info(JSON.toJSONString(resultMap));
                if(!SignUtils.checkParam(resultMap, Config.key)){

                    res.setResultCode("-1");
                    res.setResultMessage("验证签名不通过");
                    res.setResult(resultMap);
                    logger.info("验证签名不通过");
                    return res;
                }
                resultMap.put("proxUrl",Config.proxurl);
                res.setResultCode("0");
                res.setResultMessage("成功");
                res.setResult(resultMap);
                return res;
            }else{
                res.setResultCode("-1");
                res.setResultMessage("未响应");
                logger.error("请求无响应");
                return res;
            }
        }catch (Exception e) {
            e.printStackTrace();
            res.setResultCode("-1");
            res.setResultMessage("系统异常请稍后重试");
            logger.error("系统异常");
            return res;
        }
    }

    @Override
    public openServerResponse JH_GetQrcode(JHQrcodeRequest arg0) {
    	String bankURL=jhConfig.getBASEURL();
	    //bankURL="http://128.128.97.200:8101/CCBIS/ccbMain";
	        
		String MERCHANTID = jhConfig.getMERCHANTID();
        String POSID = jhConfig.getPOSID();
        String BRANCHID = jhConfig.getBRANCHID();
        String ORDERID = arg0.getORDERID();
        String PAYMENT= arg0.getPAYMENT().toString();
        String CURCODE="01";
        String TXCODE = "530550";
        String REMARK1 = arg0.getBODY();
        String REMARK2 = "";
        String RETURNTYPE="3";
        String TIMEOUT = "";
        String PUB32TR2= jhConfig.getPUB();
        
        StringBuffer tmp = new StringBuffer(); //验签字段
        tmp.append("MERCHANTID=");
        tmp.append(MERCHANTID);
        tmp.append("&POSID=");
        tmp.append(POSID);
        tmp.append("&BRANCHID=");
        tmp.append(BRANCHID);
        tmp.append("&ORDERID=");
        tmp.append(ORDERID);
        tmp.append("&PAYMENT=");
        tmp.append(PAYMENT);
        tmp.append("&CURCODE=");
        tmp.append(CURCODE);
        tmp.append("&TXCODE=");
        tmp.append(TXCODE);
        tmp.append("&REMARK1=");
        tmp.append(REMARK1);
        tmp.append("&REMARK2=");
        tmp.append(REMARK2);
        tmp.append("&RETURNTYPE=");
        tmp.append(RETURNTYPE);
        tmp.append("&TIMEOUT=");
        tmp.append(TIMEOUT);
        tmp.append("&PUB=");
        tmp.append(PUB32TR2);

        Map map = new HashMap();
        map.put("CCB_IBSVersion","V6");	//必输项
        map.put("MERCHANTID",MERCHANTID);
        map.put("BRANCHID",BRANCHID);
        map.put("POSID",POSID);
        map.put("ORDERID",ORDERID);
        map.put("PAYMENT",PAYMENT);
        map.put("CURCODE",CURCODE);
        map.put("TXCODE",TXCODE);
        map.put("REMARK1",REMARK1);
        map.put("REMARK2",REMARK2);
        map.put("RETURNTYPE",RETURNTYPE);
        map.put("TIMEOUT",TIMEOUT);
        map.put("MAC",MD5.jh_sign(tmp.toString(), "", "UTF-8"));
        openServerResponse response = new openServerResponse();
        try{
            logger.info("获取二维码-第一步请求："+JSON.toJSONString(map));
            String ret = HttpClientUtil.httpPost(bankURL, map);
            logger.info("获取二维码-第一步响应："+ret);
            map =JSON.toJavaObject((JSON)JSON.parse(ret), Map.class);
            logger.info("获取二维码-第二步请求:"+map.get("PAYURL").toString());
            ret = HttpClientUtil.httpGet(map.get("PAYURL").toString(), "UTF-8");
            logger.info("获取二维码-第二步响应:"+ret);
            map=JSON.toJavaObject((JSON)JSON.parse(ret), Map.class);
            map.put("QRURL", URLDecoder.decode(map.get("QRURL").toString()));
            map.put("PROXURL",jhConfig.getProxurl());
            response.setResult(map);
            response.setResultCode("0");
            response.setResultMessage("二维码生成成功");
            return response;
        }catch (Exception ex){
            logger.info(ex.getMessage());
            response.setResultCode("-1");
            response.setResultMessage("系统异常，请重新下单");
            return response;
        }
    }

    @Override
    public openServerResponse JH_QueryOrder(JHQrcodeRequest arg0) {
        //1.创建客户端Socket，指定服务器地址和端口
        openServerResponse response = new openServerResponse();

        String str ="<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?><TX><REQUEST_SN>"+ System.currentTimeMillis()+"</REQUEST_SN><CUST_ID>"+jhConfig.getMERCHANTID()+"</CUST_ID><USER_ID>"+jhConfig.getUserid()+"</USER_ID><PASSWORD>"+jhConfig.getPwd()+"</PASSWORD><TX_CODE>5W1002</TX_CODE><LANGUAGE>CN</LANGUAGE><TX_INFO><START></START>" +
                "<STARTHOUR></STARTHOUR>" +
                "<STARTMIN></STARTMIN>" +
                "<END></END>" +
                "<ENDHOUR></ENDHOUR>" +
                "<ENDMIN></ENDMIN>" +
                "<KIND>0</KIND>" +
                "<ORDER>"+arg0.getORDERID()+"</ORDER>" +
                "<ACCOUNT></ACCOUNT>" +
                "<DEXCEL>1</DEXCEL>" +
                "<MONEY></MONEY>" +
                "<NORDERBY>2</NORDERBY>" +
                "<PAGE>1</PAGE>" +
                "<POS_CODE>"+jhConfig.getPOSID()+"</POS_CODE>" +
                "<STATUS>3</STATUS>" +
                "<Mrch_No></Mrch_No></TX_INFO><SIGN_INFO></SIGN_INFO><SIGNCERT></SIGNCERT></TX>" ;
        logger.info("查询请求:"+str);
        Socket socket = null;
        PrintWriter pw=null;
        BufferedReader br=null;
        try {
            socket = new Socket(jhConfig.getSocketAddress(),jhConfig.getSocketPort());
            br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GB18030"));
            pw=new PrintWriter(socket.getOutputStream());
            pw.print(str);
            pw.flush();
            socket.shutdownOutput();
            String sLine=null;
            StringBuffer sb = new StringBuffer();
            while ((sLine=br.readLine())!=null){
                sb.append(sLine);
            }

            br.close();
            pw.close();
            socket.close();
            logger.info("查询响应："+sb.toString());
            Document doc = DocumentHelper.parseText(sb.toString());
            response.setResultCode(doc.selectSingleNode("//RETURN_CODE").getText());
            response.setResultMessage(doc.selectSingleNode("//RETURN_MSG").getText());
            if(response.getResultCode().equals("000000")){
                Map<String,String> map = new HashMap<>();
                map.put("orderStatus",doc.selectSingleNode("//ORDER_STATUS").getText());
                map.put("paymentMoney",doc.selectSingleNode("//PAYMENT_MONEY").getText());
                map.put("refundMoney",doc.selectSingleNode("//REFUND_MONEY").getText());
                response.setResult(map);
            }
            return response;
        } catch (IOException e) {
            logger.info(e.getMessage());
            response.setResultCode("-1");
            response.setResultMessage("系统发生错误，请稍后重试");
            return response;
        } catch (DocumentException e) {
            logger.info(e.getMessage());
            response.setResultCode("-1");
            response.setResultMessage("系统发生错误，请稍后重试");
            return response;
        }
    }

    @Override
    public openServerResponse JH_RefundOrder(JHQrcodeRequest arg0) {
        //1.创建客户端Socket，指定服务器地址和端口
        openServerResponse response = new openServerResponse();

       String str ="<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?><TX><REQUEST_SN>"+ System.currentTimeMillis()+"</REQUEST_SN><CUST_ID>"+jhConfig.getMERCHANTID()+"</CUST_ID><USER_ID>"+jhConfig.getUserid()+"</USER_ID><PASSWORD>"+jhConfig.getPwd()+"</PASSWORD><TX_CODE>5W1004</TX_CODE><LANGUAGE>CN</LANGUAGE><TX_INFO><MONEY>"+arg0.getPAYMENT()+"</MONEY><ORDER>"+arg0.getORDERID()+"</ORDER><REFUND_CODE>"+arg0.getREFUND_CODE()+"</REFUND_CODE></TX_INFO><SIGN_INFO></SIGN_INFO><SIGNCERT></SIGNCERT></TX>" ;
        logger.info("退款请求:"+str);
        Socket socket = null;
        PrintWriter pw=null;
        BufferedReader br=null;
        try {
            socket = new Socket(jhConfig.getSocketAddress(),jhConfig.getSocketPort());
            br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GB18030"));
            pw=new PrintWriter(socket.getOutputStream());
            pw.print(str);
            pw.flush();
            socket.shutdownOutput();
            String sLine=null;
            StringBuffer sb = new StringBuffer();
            while ((sLine=br.readLine())!=null){
                sb.append(sLine);
            }

            br.close();
            pw.close();
            socket.close();
            logger.info("退款响应："+sb.toString());
            Document doc = DocumentHelper.parseText(sb.toString());
            response.setResultCode(doc.selectSingleNode("//RETURN_CODE").getText());
            response.setResultMessage(doc.selectSingleNode("//RETURN_MSG").getText());
            return response;
        } catch (IOException e) {
            logger.info(e.getMessage());
            response.setResultCode("-1");
            response.setResultMessage("系统发生错误，请稍后重试");
            return response;
        } catch (DocumentException e) {
            logger.info(e.getMessage());
            response.setResultCode("-1");
            response.setResultMessage("系统发生错误，请稍后重试");
            return response;
        }


    }

    @Override
    public openServerResponse JH_CloseOrder(JHQrcodeRequest arg0) {
        String bankURL="https://ibsbjstar.ccb.com.cn/CCBIS/B2CMainPlat_00";
        //bankURL="http://128.128.97.200:8101/CCBIS/ccbMain";

        String MERCHANTID = jhConfig.getMERCHANTID();
        String POSID = jhConfig.getPOSID();
        String BRANCHID = jhConfig.getBRANCHID();
        String ORDERID = arg0.getORDERID();


        String TXCODE = "530559";

        String PUB32TR2= jhConfig.getPUB();

        StringBuffer tmp = new StringBuffer(); //验签字段
        tmp.append("MERCHANTID=");
        tmp.append(MERCHANTID);
        tmp.append("&POSID=");
        tmp.append(POSID);
        tmp.append("&BRANCHID=");
        tmp.append(BRANCHID);
        tmp.append("&ORDERID=");
        tmp.append(ORDERID);

        tmp.append("&TXCODE=");
        tmp.append(TXCODE);
       tmp.append("&SUB_APPID=");
        tmp.append("&PUB=");
        tmp.append(PUB32TR2);

        Map map = new HashMap();
        map.put("CCB_IBSVersion","V6");	//必输项
        map.put("MERCHANTID",MERCHANTID);

        map.put("POSID",POSID);
        map.put("BRANCHID",BRANCHID);
        map.put("ORDERID",ORDERID);

        map.put("TXCODE",TXCODE);
       map.put("SUB_APPID","");
        map.put("MAC",MD5.jh_sign(tmp.toString(), "", "UTF-8"));
        openServerResponse response = new openServerResponse();
        try{
            logger.info("关闭订单请求："+JSON.toJSONString(map));
            String ret = HttpClientUtil.httpPost(bankURL, map);
            logger.info("关闭订单响应:"+ret);
            map=JSON.toJavaObject((JSON)JSON.parse(ret), Map.class);

            response.setResult(map);
            response.setResultCode("0");
            response.setResultMessage("请求成成功");

            return response;
        }catch (Exception ex){
            logger.info(ex.getMessage());
            response.setResultCode("-1");
            response.setResultMessage("系统异常，关闭订单失败");
            return response;
        }
    }
    @Override
    public String getYBDY(String name) {
        try{
            List l = hisDao.queryLike(name);
            if (l == null || l.size() <= 0) {
                return "-1";
            }
            if (l.size() > 1) {
                return "-3";
            }

            Map<String,Object> m = (Map) l.get(0);
            String result= m.get("ARCIM_CODE") +","+m.get("ARCIM_Desc")+","+m.get("TARI_CODE")+","+m.get("TARI_Desc")+","+m.get("INTCT_InsuCode")+","+m.get("INTCT_InsuDesc");


            return result;
        }catch (Exception ex){
            return "-2";
        }

    }
    @Override
    public String getJSYBDY(String name) {
        try{
            List l=hisDao.query(name);
            if (l == null || l.size() <= 0) {
                return "-1";
            }
            if (l.size() > 1) {
                return "-3";
            }
            Map m = (Map) l.get(0);
            String result= m.get("ARCIM_CODE") +","+m.get("ARCIM_Desc")+","+m.get("TARI_CODE")+","+m.get("TARI_Desc")+","+m.get("INTCT_InsuCode")+","+m.get("INTCT_InsuDesc")+m.get("TAROC_Code")+","+m.get("TARI_OutpatCate");
            return result ;
        }catch (Exception ex){
            return "-2";
        }

    }


    @Override
    public CDResponse ydjy_common_register_cancel(String zzjcode,String zzjname,String akc190, String aac002, String aac003) {
return null;
//        CDResponse cdResponse = new CDResponse();
//        String params = "<?xml version=\"1.0\" encoding=\"GBK\"?>"+
//                "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
//                "<soap:Header>" +
//                "<in:system xmlns:in=\"http://www.ylzinfo.com/\">" +
//                "<para usr=\""+ybjjcode+"\"/>" +
//                "<para pwd=\""+pwd+"\"/>" +
//                "<para machineid=\"1000\"/>"+
//                "<para sid=\"ydjy_common_register_cancel\"/>" +
//                "</in:system>" +
//                "</soap:Header>" +
//                "<soap:Body>" +
//                "<in:business xmlns:in=\"http://www.ylzinfo.com/\">" +
//                "<para akb020=\"02\"/>"+
//                "<para aac002=\"" + aac002 + "\"/>"+
//        "<para aac003=\"" + aac003 + "\"/>"+
//        "<para aae011=\""+zzjcode+"\"/>"+
//        "<para akc190=\"" + akc190 + "\"/>"+
//        "<para xae011=\""+zzjname+"\"/>"+
//        "<para aae036=\"" + DateUtil.formatDate(new Date(),"yyyy-MM:dd HH:mm:ss") + "\"/>"+
//                "</in:business>" +
//                "</soap:Body>" +
//                "</soap:Envelope>";;
//        try {
//            Object[] objects= new Object[]{ybjjcode,pwd,"1000",params};
//            Object[] object = client.invoke("ydjy_common_register_cancel", objects);
//            String ybStr=object[0].toString();
//            System.out.println(ybStr);
//            if(ybStr.indexOf("information")>0){
//                cdResponse.setResultCode("-2");
//
//                cdResponse.setReesultMsg(ybStr);
//                return cdResponse;
//            }
//            cdResponse.setResultCode("0");
//
//            cdResponse.setReesultMsg(ybStr);
//            return cdResponse;
//        } catch (Exception e) {
//            cdResponse.setResultCode("-1");
//            cdResponse.setReesultMsg(e.getMessage());
//            return cdResponse;
//        }
    }

    @Override
    public CDResponse ydjy_common_inpatientleave_cancel(String zzjcode,String zzjname,String akc190, String bcc002, String bcc001, String aac002) {
        return null;
//        CDResponse cdResponse = new CDResponse();
//        String params = "<?xml version=\"1.0\" encoding=\"GBK\"?>"+
//                "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
//                "<soap:Header>" +
//                "<in:system xmlns:in=\"http://www.ylzinfo.com/\">" +
//                "<para usr=\""+ybjjcode+"\"/>" +
//                "<para pwd=\""+pwd+"\"/>" +
//                "<para machineid=\"1000\"/>"+
//                "<para sid=\"ydjy_common_inpatientleave_cancel\"/>" +
//                "</in:system>" +
//                "</soap:Header>" +
//                "<soap:Body>" +
//                "<in:business xmlns:in=\"http://www.ylzinfo.com/\">" +
//                "<para akb020=\"02\"/>"+
//                "<para aac002=\"" + aac002 + "\"/>"+
//                "<para bcc001=\"" + bcc001 + "\"/>"+
//                "<para bcc002=\"" + bcc002 + "\"/>"+
//                "<para aae011=\""+zzjcode+"\"/>"+
//                "<para akc190=\"" + akc190 + "\"/>"+
//                "<para xae011=\""+zzjname+"\"/>"+
//                "<para aae036=\"" + DateUtil.formatDate(new Date(),"yyyy-MM:dd HH:mm:ss") + "\"/>"+
//                "</in:business>" +
//                "</soap:Body>" +
//                "</soap:Envelope>";;
//        try {
//            Object[] objects= new Object[]{ybjjcode,pwd,"1000",params};
//            Object[] object = client.invoke("ydjy_common_inpatientleave_cancel", objects);
//            String ybStr=object[0].toString();
//            System.out.println(ybStr);
//            if(ybStr.indexOf("information")>0){
//                cdResponse.setResultCode("-2");
//
//                cdResponse.setReesultMsg(ybStr);
//                return cdResponse;
//            }
//            cdResponse.setResultCode("0");
//
//            cdResponse.setReesultMsg(ybStr);
//            return cdResponse;
//        } catch (Exception e) {
//            cdResponse.setResultCode("-1");
//            cdResponse.setReesultMsg(e.getMessage());
//            return cdResponse;
//        }
    }






}
